<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastAPI MySQL CRUD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .card {
            transition: transform 0.2s;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .category-badge {
            cursor: pointer;
        }
        .form-container {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="text-center mb-5">
            <h1 class="display-4 fw-bold text-primary">
                <i class="bi bi-database"></i> Product Manager
            </h1>
            <p class="lead">Manage products with FastAPI and MySQL</p>
        </div>

        <!-- 产品表单 -->
        <div class="row mb-5">
            <div class="col-md-6 mx-auto form-container">
                <h3 class="mb-4" id="form-title">Add New Product</h3>
                <form id="product-form">
                    <input type="hidden" id="product-id">
                    <div class="mb-3">
                        <label for="name" class="form-label">Product Name</label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="price" class="form-label">Price ($)</label>
                            <input type="number" class="form-control" id="price" min="0" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="category" class="form-label">Category</label>
                            <input type="text" class="form-control" id="category" required>
                        </div>
                    </div>
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="reset" class="btn btn-outline-secondary">Reset</button>
                        <button type="submit" class="btn btn-primary">Save Product</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 分类过滤 -->
        <div class="d-flex justify-content-center mb-4">
            <div class="btn-group" id="category-filter">
                <button class="btn btn-outline-primary active" data-category="all">All Products</button>
                <!-- 分类将通过JS动态添加 -->
            </div>
        </div>

        <!-- 产品列表 -->
        <div class="row" id="products-container">
            <!-- 产品卡片将通过JS动态添加 -->
        </div>
    </div>

    <!-- 模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this product?</p>
                    <p class="fw-bold" id="delete-product-name"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirm-delete">Delete</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentProductId = null;
        let deleteProductId = null;

        // DOM 加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 加载产品和分类
            fetchProducts();
            fetchCategories();

            // 表单提交处理
            document.getElementById('product-form').addEventListener('submit', handleFormSubmit);

            // 删除确认按钮
            document.getElementById('confirm-delete').addEventListener('click', handleDelete);
        });

        // 获取所有产品
        async function fetchProducts(category = 'all') {
            const url = category === 'all'
                ? '/api/products/'
                : `/api/products/?category=${category}`;

            try {
                const response = await fetch(url);
                const products = await response.json();
                renderProducts(products);
            } catch (error) {
                console.error('Error fetching products:', error);
                showAlert('Failed to load products', 'danger');
            }
        }

        // 获取所有分类
        async function fetchCategories() {
            try {
                const response = await fetch('/api/categories/');
                const categories = await response.json();
                renderCategoryFilter(categories);
            } catch (error) {
                console.error('Error fetching categories:', error);
            }
        }

        // 渲染产品列表
        function renderProducts(products) {
            const container = document.getElementById('products-container');
            container.innerHTML = '';

            if (products.length === 0) {
                container.innerHTML = `
                    <div class="col-12 text-center py-5">
                        <h4 class="text-muted">No products found</h4>
                        <p>Add your first product using the form above</p>
                    </div>
                `;
                return;
            }

            products.forEach(product => {
                const productCard = `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">${product.name}</h5>
                                <h6 class="card-subtitle mb-2 text-muted">$${product.price}</h6>
                                <p class="card-text">${product.description || 'No description'}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="badge bg-primary category-badge">${product.category}</span>
                                    <div>
                                        <button class="btn btn-sm btn-outline-primary edit-btn"
                                                data-id="${product.id}">
                                            <i class="bi bi-pencil"></i> Edit
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete-btn"
                                                data-id="${product.id}"
                                                data-name="${product.name}"
                                                data-bs-toggle="modal"
                                                data-bs-target="#deleteModal">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                container.innerHTML += productCard;
            });

            // 添加编辑按钮事件
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const productId = this.getAttribute('data-id');
                    loadProductForEdit(productId);
                });
            });

            // 添加删除按钮事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    deleteProductId = this.getAttribute('data-id');
                    document.getElementById('delete-product-name').textContent =
                        `"${this.getAttribute('data-name')}"`;
                });
            });

            // 添加分类过滤事件
            document.querySelectorAll('.category-badge').forEach(badge => {
                badge.addEventListener('click', function() {
                    const category = this.textContent.trim();
                    document.querySelectorAll('#category-filter .btn').forEach(btn => {
                        btn.classList.remove('active');
                    });
                    document.querySelector(`#category-filter .btn[data-category="${category}"]`)
                        .classList.add('active');
                    fetchProducts(category);
                });
            });
        }

        // 渲染分类过滤器
        function renderCategoryFilter(categories) {
            const container = document.getElementById('category-filter');
            categories.forEach(category => {
                const categoryBtn = `
                    <button class="btn btn-outline-primary"
                            data-category="${category}">
                        ${category}
                    </button>
                `;
                container.innerHTML += categoryBtn;
            });

            // 添加分类过滤事件
            document.querySelectorAll('#category-filter .btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('#category-filter .btn').forEach(b => {
                        b.classList.remove('active');
                    });
                    this.classList.add('active');
                    const category = this.getAttribute('data-category');
                    fetchProducts(category);
                });
            });
        }

        // 加载产品进行编辑
        async function loadProductForEdit(productId) {
            try {
                const response = await fetch(`/api/products/${productId}`);
                const product = await response.json();

                // 填充表单
                document.getElementById('product-id').value = product.id;
                document.getElementById('name').value = product.name;
                document.getElementById('description').value = product.description || '';
                document.getElementById('price').value = product.price;
                document.getElementById('category').value = product.category;

                // 更新表单标题
                document.getElementById('form-title').textContent = `Edit Product: ${product.name}`;

                // 滚动到表单
                document.querySelector('.form-container').scrollIntoView({
                    behavior: 'smooth'
                });

                currentProductId = productId;
            } catch (error) {
                console.error('Error loading product for edit:', error);
                showAlert('Failed to load product details', 'danger');
            }
        }

        // 处理表单提交
        async function handleFormSubmit(e) {
            e.preventDefault();

            const product = {
                name: document.getElementById('name').value,
                description: document.getElementById('description').value,
                price: parseInt(document.getElementById('price').value),
                category: document.getElementById('category').value
            };

            const productId = document.getElementById('product-id').value;
            const method = productId ? 'PUT' : 'POST';
            const url = productId ? `/api/products/${productId}` : '/api/products/';

            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(product)
                });

                if (response.ok) {
                    const result = await response.json();

                    // 重置表单
                    document.getElementById('product-form').reset();
                    document.getElementById('product-id').value = '';
                    document.getElementById('form-title').textContent = 'Add New Product';

                    // 刷新产品列表
                    fetchProducts();

                    showAlert(
                        productId
                            ? `Product "${result.name}" updated successfully`
                            : `Product "${result.name}" created successfully`,
                        'success'
                    );

                    currentProductId = null;
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || 'Unknown error');
                }
            } catch (error) {
                console.error('Error saving product:', error);
                showAlert(`Failed to save product: ${error.message}`, 'danger');
            }
        }

        // 处理删除
        async function handleDelete() {
            if (!deleteProductId) return;

            try {
                const response = await fetch(`/api/products/${deleteProductId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                    modal.hide();

                    // 刷新产品列表
                    fetchProducts();

                    showAlert('Product deleted successfully', 'success');
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || 'Unknown error');
                }
            } catch (error) {
                console.error('Error deleting product:', error);
                showAlert(`Failed to delete product: ${error.message}`, 'danger');
            } finally {
                deleteProductId = null;
            }
        }

        // 显示通知
        function showAlert(message, type) {
            // 移除现有通知
            const existingAlert = document.querySelector('.alert');
            if (existingAlert) existingAlert.remove();

            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show fixed-top m-3`;
            alert.role = 'alert';
            alert.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;

            document.body.prepend(alert);

            // 5秒后自动消失
            setTimeout(() => {
                alert.classList.remove('show');
                setTimeout(() => alert.remove(), 150);
            }, 5000);
        }
    </script>
</body>
</html>